package com.atguigu.gmall.common.feign;

import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.UserAuthToUtil;
import com.atguigu.gmall.model.to.UserAuthTo;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2024/10/5 8:14
 */

public class UserHeaderRequestInterceptor implements RequestInterceptor {
    //在请求模板中放入透传的请求头
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes!=null){
            HttpServletRequest request = requestAttributes.getRequest();
            String userId = request.getHeader("userId");
            if (userId != null) {
                requestTemplate.header("UserId", userId);
            }
            String userTempId = request.getHeader("userTempId");
            if (userTempId != null) {
                requestTemplate.header("UserTempId",userTempId);
            }
        }else {
            throw new GmallException(ResultCodeEnum.REQUEST_FEIGN_HEADER_LOSE);
        }


    }
}
